﻿using System;
using System.Windows;
using System.Windows.Input;
using WickedFlame.Core.Shapes;
using WickedFlame.Core.Tools;

namespace WickedFlame.Core.Tools
{
    public class PolygonTool : FactoryTool
    {
        PolygonShape curentPath;

        public PolygonTool()
            : base()
        {
        }

        protected override VectorShape CreateShape(Point mousePosition)
        {
            curentPath = new PolygonShape(mousePosition);

            curentPath.StrokeThickness = ShapePropertySettings.Settings.StrokeThickness;
            curentPath.Stroke = ShapePropertySettings.Settings.Stroke;

            curentPath.AddLineSegment(mousePosition);

            return curentPath;
        }

        public override void OnMouseLeftButtonDown(DrawingCanvas sender, MouseButtonEventArgs e)
        {
            //create new object if none exists
            if (curentPath == null)
            {
                sender.AddShape(CreateShape(Mouse.GetPosition(sender)));
                return;
            }

            //add new path to curentpath
            curentPath.AddLineSegment(Mouse.GetPosition(sender));
        }

        public override void OnMouseLeftButtonUp(DrawingCanvas sender, MouseButtonEventArgs e)
        {
            var shape = sender.SelectedLayer.ShapeList.TopShape as PolygonShape;
            if (shape != null)
                shape.CallChangeEndHandler();
        }

        public override void OnMouseMove(DrawingCanvas sender, MouseEventArgs e)
        {
            if (curentPath != null)
            {
                Point m = Mouse.GetPosition(sender);
                if (curentPath != null)
                    curentPath.MoveTracker(m, curentPath.MaxHandle);
            }
        }

        public override void OnMouseRightButtonUp(DrawingCanvas sender, MouseButtonEventArgs e)
        {
            //Add object to history
            sender.PushHistoryCommand(new WickedFlame.Core.History.AddCommand(curentPath, sender.SelectedLayerIndex));

            //end of object
            curentPath = null;
        }
    }
}
